﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Business.Common;
using NetDon.OA.Business.Sequentials;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Data.HelperClasses;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.Configuration;
using NetDon.OA.Portal.Constants;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Shunting
{
    //[Command(ButtonConstants.CommandNames.Save, ButtonConstants.CommandImages.Save, Order = 0, CausesValidation = true)]
    [Navigation("干线流程", "出单信息录入")]
    public partial class IssuingOrderInfoSingleEdit : PageBase
    {
        private  StringBuilder sb =new StringBuilder();
        #region Properties
        protected Guid Id
        {
            get
            {
                return Parameters.GetGuid("Id");
            }
        }

        private static readonly string[] AvialableFileExtensions = new[]
                                                              {
                                                                  // Office Open XML
                                                                  ".XLSX", ".XLSM",
                                                                  // Excel Binary
                                                                  ".XLSB",
                                                                  // Excel 97-2003
                                                                  ".XLS"
                                                              };

        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                this.IssuringOrderEditUC.LoadUserControl(Guid.Empty);

            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IssuringOrderEditUC.SaveOrder())
            {

            }

        }

        protected void btnSaveAndNew_Click(object sender, EventArgs e)
        {
            if (IssuringOrderEditUC.SaveOrder())
            {
                IssuringOrderEditUC.LoadNavigationView(Guid.Empty);
            }
        }
        protected void btnImportIssuringOrderInfo_Click(object sender, EventArgs e)
        {
            if (!FileUpload.HasFile)
            {
                Alert("请选择要导入的出单信息文件.");
                return;
            }
            string extension = Path.GetExtension(FileUpload.FileName);
            if (AvialableFileExtensions.FirstOrDefault(i => string.Compare(i, extension, true) == 0) == null)
            {
                Alert("请选择正确的Excel文件.");
                return;
            }

            string filePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(FileUpload.FileName));
            FileUpload.SaveAs(filePath);
            var data = DataImportService.ReadExcelData(filePath);
            // 1st step: check whether the uploaded excel file has data.
            if (!HasData(data))
            {
                Alert("你导入的Excel文件没有数据.");
                return;
            }
            try
            {
                //2st insert data
                ImportData(data);
                Alert("导入成功.");
            }
            catch (ApplicationException ex)
            {

                Alert("导入的数据有问题，请核实." + ex.Message);
            }
            catch (Exception ex)
            {

                Alert("导入失败." + ex.Message);
            }
            finally
            {
                if(!string.IsNullOrWhiteSpace(sb.ToString()))
                {
                    Alert(sb.ToString());
                }
            }
        }

        private void ImportData(IList<DataImportService.IssuingOrderImportData> data)
        {
            var service = ServiceContainer.GetService<IIssuingOrderService>();
            var issuingOrders = new Dictionary<string, IssuingOrderData>();
            foreach (var issuingOrderImportData in data)
            {
                if (string.IsNullOrWhiteSpace(issuingOrderImportData.DeliveryOrderCode))
                {
                    throw new Exception("请输入交货单号！");
                }
                if (string.IsNullOrWhiteSpace(issuingOrderImportData.TransportationPlanCode))
                {
                    throw new Exception("请输入运输计划号（交货单号{0})！".Formato(issuingOrderImportData.DeliveryOrderCode));
                }

                if (WebConfig.IsCalculateByWeight(issuingOrderImportData.GoodsShippedType))
                {
                    if (!issuingOrderImportData.OrderWeight.HasValue || issuingOrderImportData.OrderWeight.Value <= 0)
                    {
                        throw new Exception("请输入下单重量（交货单号{0})！".Formato(issuingOrderImportData.DeliveryOrderCode));
             
                    }

                }
                else
                {
                    if (!issuingOrderImportData.OrderVolumn.HasValue || issuingOrderImportData.OrderVolumn.Value <= 0)
                    {
                        throw new Exception("请输入下单材积（交货单号{0})！".Formato(issuingOrderImportData.DeliveryOrderCode));
                   
                    }
                }

                IssuingOrderData issuingOrder = null;
                if (issuingOrders.ContainsKey(issuingOrderImportData.TransportationPlanCode))
                    issuingOrder = issuingOrders[issuingOrderImportData.TransportationPlanCode];

             
                if (issuingOrder == null)
                {
                    issuingOrder = new IssuingOrderData()
                                       {
                                           Id = Guid.NewGuid(),
                                           AreaId = CurrentApplicationContext.CompanyId,
                                           OrderStatus = OrderStatus.Submitted,
                                           CustomerId = GetClientId(issuingOrderImportData.CustomerId),
                                           TransportationPlanCode = issuingOrderImportData.TransportationPlanCode,
                                           ReceivingOrderDate = issuingOrderImportData.ReceivingOrderDate,
 EntruckingAddress =
                                               GetDataDictionary(issuingOrderImportData.EntruckingAddress,CurrentApplicationContext.CompanyId, "装货地点"),
                                           GoodsShippedTypeId =
                                               GetDataDictionary(issuingOrderImportData.GoodsShippedType, CurrentApplicationContext.CompanyId,"承运货物"),
                                           RouteTypeId = GetDataDictionary(issuingOrderImportData.RouteType, CurrentApplicationContext.CompanyId,"线路分类"),
                                           DeliveryProvince = GetProvince(issuingOrderImportData.Province),

                                           OrderVehicleNumber = 1,
                                           //default,
                                           CheckoutType =  GetCheckoutType(issuingOrderImportData.CheckoutType), // CheckoutType.Whole,
                                           IssuingOrderDeliveryDataList = new List<IssuingOrderDeliveryData>(),
                                           CreatedDate = DateTime.Now,
                                           LastUpdatedDate = DateTime.Now,
                                           CreateBy = CurrentApplicationContext.UserId,
                                           LastUpdatedBy = CurrentApplicationContext.UserId,
                                           BusinessType = BusinessType.A


                                       };
                    issuingOrder.OrderCode = Sequential.Generate(SequentialKeys.CustomerOrderCode,
                                                             new OrderCodeContext
                                                             {

                                                                 CustomerCode =
                                                                     new CustomerInfoEntity(
                                                                     issuingOrder.CustomerId.Value).
                                                                     CustomerCode
                                                             });
                    issuingOrder.ShuntingCost = 0;
                    issuingOrder.ActualEntruckingAmount =  1;
                    issuingOrder.IsGoodsJilted = false;
                    issuingOrder.ActualEntruckingUnit = 0;
                    issuingOrders.Add(issuingOrderImportData.TransportationPlanCode, issuingOrder);
                }
                if (!issuingOrder.IssuingOrderDeliveryDataList.Any(e => e.DeliveryOrderCode == issuingOrderImportData.DeliveryOrderCode.Trim()))
                {
                    var list = issuingOrder.IssuingOrderDeliveryDataList.ToList();

               
                    var issuingOrderDelivery = new IssuingOrderDeliveryData()
                                                   {
                                                       AreaId = CurrentApplicationContext.CompanyId,
                                                       DeliveryCity = GetCity(issuingOrderImportData.City),
                                                       DeliveryAddress = issuingOrderImportData.DeliveryAddress,
                                                       DeliveryOrderCode = issuingOrderImportData.DeliveryOrderCode,
                                                       DeliveryOrderType =
                                                           GetDataDictionary(issuingOrderImportData.DeliveryOrderType,
                                                                             CurrentApplicationContext.CompanyId,
                                                                             "交货单类型"),
                                                       OrderQuantity = issuingOrderImportData.OrderQuantity,
                                                       OrderVolumn = issuingOrderImportData.OrderVolumn,
                                                       OrderWeight
                                                           = issuingOrderImportData.OrderWeight,
                                                       UnitCost = issuingOrderImportData.UnitCost,
                                                       CreatedDate = DateTime.Now,
                                                       LastUpdatedDate = DateTime.Now,
                                                       CreateBy = CurrentApplicationContext.UserId,
                                                       LastUpdatedBy = CurrentApplicationContext.UserId,
                                                       Id = Guid.NewGuid(),

                                                   };
                    list.Add(issuingOrderDelivery);
                    issuingOrder.IssuingOrderDeliveryDataList = list;

                    issuingOrder.OrderVolumn = issuingOrder.IssuingOrderDeliveryDataList.Sum(o => o.OrderVolumn);
                    issuingOrder.OrderWeight = issuingOrder.IssuingOrderDeliveryDataList.Sum(o => o.OrderWeight);
                    issuingOrder.OrderQuantity = issuingOrder.IssuingOrderDeliveryDataList.Sum(o => o.OrderQuantity);
                    issuingOrder.UnitCost = issuingOrder.IssuingOrderDeliveryDataList.Sum(o => o.UnitCost);
                    issuingOrder.ShuntingCost = SystemUtility.GetShuntingCost(issuingOrder.IssuingOrderDeliveryDataList,
                                                               WebConfig.IsCalculateByWeight(issuingOrder.GoodsShippedTypeId));
                }



            }
            foreach (var issuingOrderData in issuingOrders.Keys)
            {
                var issuingOrder =
                 service.GetIssuingOrderByTransportationPlanCode(issuingOrderData);
                if (issuingOrder == null && issuingOrders[issuingOrderData].IssuingOrderDeliveryDataList.Any())
                {
                    service.AddOrder(issuingOrders[issuingOrderData]);
                }
                else
                {
                     if (issuingOrder != null)
                     {
                         sb.AppendLine("运输计划号{0}已经存在，本次不再导入。</Br>".Formato(issuingOrder.TransportationPlanCode));
                         
                     }

                    
                }
            }

        }

        private CheckoutType GetCheckoutType(string checkoutType)
        {
            if(string.IsNullOrWhiteSpace(checkoutType)) return CheckoutType.Whole;
            var infos=EnumUtilities.GetInformations<CheckoutType>();
            var checkouTypeInfo = infos.FirstOrDefault(info => info.Description == checkoutType);
            if (checkouTypeInfo == null)
            {
                throw new ApplicationException("结算方式不存在！");
            }
            return EnumUtilities.Parse<CheckoutType>(checkouTypeInfo.Name);
        }




        private Guid GetClientId(string clientName)
        {
            if (string.IsNullOrWhiteSpace(clientName))
            {
                throw new ApplicationException("客户不存在！");
            }
            var client = ServiceContainer.GetService<ICustomerInfoService>().GetCustomerInfoByCode(clientName);
            if (client == null)
            {
                throw new ApplicationException("客户不存在！");
            }
            return client.CustomerId;
        }

        private Guid GetDataDictionary(string name, Guid areaId, string category)
        {
            if(string.IsNullOrWhiteSpace(name))
            {
                throw new ApplicationException("{0}不存在！".Formato(category));
            }
            var client = ServiceContainer.GetService<IDictionaryService>().GetDictionaryDataByName(name, areaId);
            if (client == null)
            {
                throw new ApplicationException("{0}不存在！".Formato(category));
            }
            return client.Value;
        }


        private string GetProvince(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ApplicationException("该省份不存在！");
            }
            var client = ServiceContainer.GetService<ILocationService>().GetProvinceByName(name);
            if (client == null)
            {
                throw new ApplicationException("该省份不存在！");
            }
            return client.ProvinceId;
        }


        private string GetCity(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ApplicationException("该城市不存在！");
            }
            var client = ServiceContainer.GetService<ILocationService>().GetCityByName(name);
            if (client == null)
            {
                throw new ApplicationException("该城市不存在！");
            }
            return client.CityId;
        }

        private static bool HasData(IList<DataImportService.IssuingOrderImportData> ds)
        {
            if (ds == null)
            {
                return false;
            }
            if (ds.Count == 0)
            {
                return false;
            }
            return true;
        }
    }
}